package io.afu.baseframework.utils;



import io.afu.baseframework.exceptions.BaseException;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 短链接相关的处理工具类
 */
public class ShortUrl {

    public static final String USER_AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36";

    /**
     * 获取链接所有跳转到URL
     * @param shortUrl 目标url
     * @param urls 用于存储所有跳转的url
     * @return 返回所有跳转的url
     * @throws BaseException 抛错
     */
    public static List<String> getAllUrlRedirections(String shortUrl,List<String> urls) throws BaseException {
        if (urls == null){
            urls = new ArrayList<>();
        }
        try {
            URL url = new URL(shortUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(false);
            connection.setRequestProperty("User-Agent",USER_AGENT);
            int code = connection.getResponseCode();
            String theUrl = connection.getHeaderField("Location");

            if (code == 301 || code == 302){
                if (theUrl.startsWith("http")){
                    urls.add(theUrl);
                    if (notInList(urls,theUrl)){
                        ShortUrl.getAllUrlRedirections(theUrl,urls);
                    }
                }else if (theUrl.startsWith("/")){
                    String urlWithoutPath = UrlUtils.getUrlWithoutPath(shortUrl);
                    String fullUrl = urlWithoutPath+theUrl;
                    urls.add(fullUrl);
                    if (notInList(urls,fullUrl)){
                        ShortUrl.getAllUrlRedirections(fullUrl,urls);
                    }
                }else {
                    String fatherPath = UrlUtils.getCurrentPath(shortUrl);
                    String fullUrl = fatherPath+theUrl;
                    urls.add(fullUrl);
                    // 防止无限重定向的产生 导致程序死循环。
                    if (notInList(urls,fullUrl)){
                        ShortUrl.getAllUrlRedirections(fullUrl,urls);
                    }
                }
            }
        }catch (Exception e){
            throw new BaseException("短网址访问出错");
        }
        return urls;
    }

    public static Boolean notInList(List<String> theList,String toCompare) {
        Boolean status = true;
        for (String str:theList){
            if (str.equals(toCompare)){
                return false;
            }
        }
        return status;
    }

    public static String getLastDomainOfFirstUrl(String shortUrl) throws BaseException{
        List<String> urls = new ArrayList<>() ;
        urls = ShortUrl.getAllUrlRedirections(shortUrl,urls);
        String lastUrl = urls.get(urls.size()-1);
        String lastUrlDomain = UrlUtils.getDomain(lastUrl);
        if (lastUrlDomain == null){
            return lastUrlDomain;
        }
        for (String url:urls){
            String domain = UrlUtils.getDomain(url);
            if (domain != null){
                if (lastUrlDomain.equals(domain)){
                    return url;
                }
            }
        }
        return lastUrl;
    }

    public static void main(String[] args){
        try {
            List<String> urls = new ArrayList<>() ;
            urls = ShortUrl.getAllUrlRedirections("https://www.vpsmm.com/g2/aHR0cHM6Ly96aGV5ZS5pby9hZmYucGhwP2FmZj04NQ==",urls);
            for (String x :urls){
                System.out.println("URL为"+x);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }


}
